package hn.cch.service.impl;

import hn.cch.controller.ProductController;
import hn.cch.message.Response;
import hn.cch.service.ProductService;
import hn.cch.entity.Product;
import hn.cch.repository.ProductRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.stream.IIOByteBuffer;
import javax.persistence.criteria.CriteriaBuilder.In;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

    public static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);


    @Autowired
    private ProductRepository productRepository;

    @Override
    public Product findById(Integer id){
        Optional<Product> optional = productRepository.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }

    @Override
    public Product save(Product product){
        return productRepository.save(product);
    }

    /**
     * 减少库存
     * @param id
     * @param stock
     * @return
     */
    @Override
    public Response<Product> subAny(Integer id, Integer stock){
        Product product = findById(id);
        if (product == null){
            logger.error("查询商品为空");
            return Response.failure();
        }
        Integer temp = product.getProductStock() - stock;
        if (temp < 0){
            logger.error("商品库存不足");
            return Response.failure();
        }
        product.setProductStock(temp);
        product = save(product);
        Response response = Response.success();
        response.setInfo(product);
        return response;
    }

}

